
import * as vscode from 'vscode';
import * as path from 'path';
import { Service } from './service';


class TreeItemNode extends vscode.TreeItem {

}

export class TreeViewProvider implements vscode.TreeDataProvider<TreeItemNode> {

  private _onDidChangeTreeData: vscode.EventEmitter<any> = new vscode.EventEmitter<any>();
  readonly onDidChangeTreeData: vscode.Event<any> = this._onDidChangeTreeData.event;

  public refresh(): any {
    this._onDidChangeTreeData.fire(undefined);
  }

  getTreeItem(element: TreeItemNode): vscode.TreeItem | Thenable<vscode.TreeItem> {
    return element;
  }

  getChildren(element?: TreeItemNode): vscode.ProviderResult<TreeItemNode[]> {
    return new Promise(async (resolve) => {
      const service = new Service();
      if (element) {
        const interfaces = await service.queryInterfaces(element.id!);
        resolve(interfaces.map(item => {
          const treeItem = new TreeItemNode(item.name);
          treeItem.tooltip = item.desc;
          treeItem.id = `${String(item.id)}`;
          treeItem.contextValue = "interface";
          treeItem.iconPath = path.join(__filename, '..', '..', 'src', '/assets/api.svg');
          // treeItem.command = { command: "mock.addAPI", title: '添加项目', arguments: [item.id] };
          return treeItem;
        }));
      } else {
        const projects = await service.queryProjects();
        resolve(projects.map(item => {
          const treeItem = new TreeItemNode(item.name);
          treeItem.id = String(item.id);
          if (!item.hasChild) {
            treeItem.collapsibleState = vscode.TreeItemCollapsibleState.Collapsed;
          }
          treeItem.description = item.name;
          treeItem.contextValue = "project";
          treeItem.iconPath = path.join(__filename, '..', '..', 'src', '/assets/project.svg');
          // treeItem.command = { command: "mock.addAPI", title: '添加项目', arguments: [item.id] };
          return treeItem;
        }));
      }


    });
  }
}